const mongoose = require('mongoose');
const MongoProduct = require('../models/product');
//const marker=require('../../tool/image');

exports.product_get_all = (req, res, next) => {
    MongoProduct.find()
        .select('name price _id')//.populate('cate','name')关联查询cate是当前表字段名,name为查询匹配的该字段
        .exec().then(result => {
            //if(result>0){
            res.status(200).json(result)
            /*}else{
                res.status(404).json({
                    error:'no found'
                })
            }*/
        }).catch(error => {
            res.status(500).json(error)
        })

}
exports.product_get_search = (req, res, next) => {//模糊搜索，可添加多个条件来匹配
    var keyword = req.query.keyword // 获取查询的字段
    MongoProduct.find({
        $or: [
            //{'description': {'$regex': keyword, $options: '$i'}},
            //{'city': {'$regex': keyword, $options: '$i'}},
            {'name': {'$regex': keyword, $options: '$i'}}//加入了$option的$i表示忽略大小写
        ]
    }).limit(10) // 最多显示10条
    .sort({'_id': -1}) // 倒序
    .exec().then(result => {
        //console.log(result,keyword)
        if(result.length>0){
            res.status(200).json(result)
        }else{
            res.status(203).json({message:'no matching results'})
        }
    }).catch(error => {
        res.status(500).json(error)
    })/**/
}
/**
 * 前端传参示例：[POST] {FROM}表单格式提交 /product
 */
exports.product_post = (req, res, next) => {
    //console.log('上传文件：',req.body,req.file)
    if(!req.file){
        return res.status(202).json({
            message:'image type error'
        })
    }
    const product = new MongoProduct({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        stock: req.body.stock,
        proImg: req.file.path
    })
    product.save().then(result => {
        //console.log(result)
        res.status(201).json(result);
        //marker.addWaterMarker();产品上传后，图片加水印
    }).catch(error => {
        res.status(500).json(error)
    })

}
/**
 * 前端传参示例：[Get] /product/5d5baa00a306f62b3cbaeb01
 */
exports.product_getById = (req, res, next) => {
    const pid = req.params.pid
    MongoProduct.findById(pid)
        .select('name price _id proImg')
        .exec().then(doc => {
            if (doc) {
                res.status(200).json(doc)
            } else {
                res.status(404).json({
                    message: 'failed pid'
                })
            }
        }).catch(error => {
            res.status(500).json(error)
        })

}
/**
 * 前端传参示例：[Patch] /product/5d5baa00a306f62b3cbaeb01
 */
exports.product_patchById = (req, res, next) => {
    const pid = req.params.pid;
    const option = {};
    for (const opt of req.body) {
        option[opt.key] = opt.value
    }
    MongoProduct.updateOne({ _id: pid }, { $set: option }).exec().then(result => {
        res.status(200).json({
            message: 'update success',
            data: result
        })
    }).catch(err => {
        res.status(500).json(err)
    })

}
/**
 * 前端传参示例：[Delete] /product/5d5baa00a306f62b3cbaeb01
 */
exports.product_deleteById = (req, res, next) => {
    const pid = req.params.pid
    MongoProduct.deleteOne({ _id: pid }).exec().then(result => {
        res.status(200).json({
            message: 'delete success',
            data: result
        })
    }).catch(err => {
        res.status(500).json(err)
    })
}
/**
 *  前端传参示例：[Delete]  {RAW}json格式传参
 * {
    "pid":[{"_id":"5d5baa00a306f62b3cbaeb01"},{"_id":"5d5ba98b0f3c190f68e55770"}]
}
 */
exports.product_deleteMany = (req, res, next) => {
    const pid = req.body.pid
    //console.log(pid);
    MongoProduct.deleteMany({ _id: {$in:pid} }).exec().then(result => {
        res.status(200).json({
            message: 'delete success',
            data: result
        })
    }).catch(err => {
        res.status(500).json({message:'no matching id'})
    })/**/
}